<?php

namespace App\Services;


use App\Models\Cms_Menu;
use App\Models\Sys_Permission;
use App\Models\Sys_Role;
use App\Traits\ResponseApi;

class RoleService
{
    public function getRoleList($params)
    {
        $result = Sys_Role::getFilter($params)->get();
        $list['list'] = $result;
        return ['status' => true,'code' => 200,'data' => $list];
    }

    public function getList($params)
    {
        $result = Sys_Role::getFilter($params)->Nodel()->paginate($params['page_size']);
        foreach ($result as $key => $value){
            $result[$key]['menu_ids'] = json_decode($value->menu_ids,true);
        }
        $list['list'] = $result;
        return ['status' => true,'code' => 200,'data' => $list];
    }

    public function getPermissionList()
    {
        $result = Sys_Permission::get();
        $list['list'] = ResponseApi::subTree($result->toArray());
        return ['status' => true,'code' => 200,'data' => $list];
    }
    public function roleAdd($params)
    {
        $ids = json_decode($params['permissions'], true);
        $_permission = Sys_Permission::whereIn('id', $ids)
            ->get()
            ->toArray();

        $menu_ids = [];
        foreach ($_permission as $item)
        {
            $menu = Cms_Menu::where('menu_key',$item['code'])->first();
            if(!empty($menu)) {
                array_push($menu_ids,$menu->id);
            }
        }
        $permissions_arr = Sys_Role::convertTrees($_permission);
        $arr['ids'] = $ids;
        $arr['permissions'] = $permissions_arr;
        $params['menu_ids'] = json_encode($menu_ids);
        $params['permissions'] = json_encode($arr);

        if(isset($params['id']) && !empty($params['id'])){
            $res = Sys_Role::where('id',$params['id'])->update($params);
            return ['status' => true,'code' => 200,'data' => $res];
        }else{
            $res = Sys_Role::create($params);
            return ['status' => true,'code' => 200,'data' => $res];
        }
    }

    public function roleDel($params)
    {
        $str = strstr((string)$params['ids'],',');

        if($str){
            $ids = explode(',',$params['ids']);
            $res = Sys_Role::whereIn('id',$ids)->update(['is_del' => 'Y']);
        }else{
            $res = Sys_Role::where('id',$params['ids'])->update(['is_del' => 'Y']);
        }

        return ['status' => true,'code' => 200,'data' => $res];
    }

}
